import getCollectionConfigs, {setGlobaleCollection} from './collectionconfigs'
const {lib, str2Runing} = ao2
const nav = Pager.nav

function onCovering() {
  const pageshead = $$('#pageshead')
  pageshead.removeClass('activeSwitch')
}

function menuDataAdapter(collectionConfigs) {
  const cloudCollection = {}
  const menus = [
    {title: '订单', itemClass: 'menu-caption', idf: 'order'},
    {title: '管理', itemClass: 'menu-caption', idf: 'manager'},
    {title: '集合管理', itemClass: 'item-icon icon-saui', attr: {tablename: '/order/collections'}, parent: 'manager'}
  ]
  
  collectionConfigs.forEach(m=>{
    const data = m.data
    const tableName = data.tableName
    const title = data.title || ''

    menus.push({
      title,
      itemClass: 'item-icon icon-saui', 
      attr: {tablename: tableName, title}, 
      parent: 'order'
    })

    if (typeof data.filds === 'string') {
      data.filds = str2Runing(data.filds)
    }

    cloudCollection[tableName] = data
  })

  setGlobaleCollection(cloudCollection)
  return menus
}

export default async function(){
  const tmps = await getCollectionConfigs()
  const menus = menuDataAdapter(tmps)
  
  const menuInst = ui_tree({
    $$id: 'admin',
    data: menus,
    itemMethod: {
      aim(e, param, inst){
        let attr = inst.attr()
        let parent = inst.parent().parent()

        // 除了集合管理页面，其他页面都指向 /order/normal 页，再由此页分发
        let url = '/order/normal' 

        if (attr.tablename === '/order/collections') {
          url = attr.tablename
          attr = {}
        }

        if (parent) {
          parent.forEach(child=>{
            if (child && child.children) {
              child.children.forEach(son=> son.removeClass('active') )
            }
          })
          inst.addClass('active')
          setTimeout(() => {
            nav.redirectTo({
              url, 
              data: attr
            })
          }, 50);
        }
        onCovering()
      }
    },
    listClass: 'router-menu-list router-menus flex-column justify-between',
  })
  return <menuInst.UI />
}
